<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\index\controller;

use app\admin\model\FavoriteModel;
use app\admin\model\MemberModel;
use app\admin\model\ShopGoodsModel;
use think\Db;
use DateTime;

class CommonController
{
    //查询单条数据
    public static function findWhereData($table, $where, $field, $order = 'id desc')
    {
        $res = Db::name($table)
            ->where($where)
            ->field($field)
            ->order($order)
            ->find();
        return $res;
    }

    //查询条件单条数据----软删除
    public static function findSoftWhereData($table, $where, $field, $except = false)
    {
        $res = Db::name($table)
            ->where($where)
            ->field($field, $except)
            ->useSoftDelete('delete_time')
            ->find();
        return $res;
    }

    //查询多条数据
    public static function selectData($table, $field, $order = 'id desc')
    {
        $res = Db::name($table)
            ->field($field)
            ->order($order)
            ->select()
            ->toArray();
        return $res;
    }

    //查询多条数据----软删除
    public static function selectSoftData($table, $field, $order = 'id desc')
    {
        $res = Db::name($table)
            ->field($field)
            ->order($order)
            ->useSoftDelete('delete_time')
            ->select()
            ->toArray();
        return $res;
    }

    //查询条件多条数据
    public static function selectWhereData($table, $where, $field, $order = 'id desc')
    {
        $res = Db::name($table)
            ->where($where)
            ->field($field)
            ->order($order)
            ->select()
            ->toArray();
        return $res;
    }

    //查询分页多条数据
    public static function selectPageData($table, $page, $field, $order = 'id desc')
    {
        $limit = config('verify.limit');
        $res = Db::name($table)
            ->field($field)
            ->page($page, $limit)
            ->order($order)
            ->select()
            ->toArray();
        return $res;
    }

    //查询条件多条数据----软删除
    public static function selectSoftWhereData($table, $where, $field, $order = 'id desc')
    {
        $res = Db::name($table)
            ->where($where)
            ->field($field)
            ->order($order)
            ->useSoftDelete('delete_time')
            ->select()
            ->toArray();
        return $res;
    }

    //查询条件分页多条数据
    public static function selectWherePageData($table, $where, $page, $field, $order = 'id desc')
    {
        $limit = config('verify.limit');
        $res = Db::name($table)
            ->where($where)
            ->field($field)
            ->page($page, $limit)
            ->order($order)
            ->select()
            ->toArray();
        return $res;
    }

    //查询条件分页多条数据----软删除
    public static function selectSoftWherePageData($table, $where, $page, $field, $order = 'id desc')
    {
        $limit = config('verify.limit');
        $res = Db::name($table)
            ->where($where)
            ->field($field)
            ->page($page, $limit)
            ->order($order)
            ->useSoftDelete('delete_time')
            ->select()
            ->toArray();
        return $res;
    }

    //查询总数聚合
    public static function totalGroup($table, $where, $group)
    {
        $res = Db::name($table)
            ->where($where)
            ->group($group)
            ->count();
        return $res;
    }

    //条件总条数
    public static function totalWhere($table, $where)
    {
        $count = Db::name($table)
            ->where($where)
            ->count();
        return $count;
    }

    //条件总页数
    public static function totalWherePage($table, $where)
    {
        $limit = config('verify.limit');
        $count = Db::name($table)
            ->where($where)
            ->count();
        return ceil($count / $limit);
    }

    //条件总页数
    public static function totalPage($table)
    {
        $limit = config('verify.limit');
        $count = Db::name($table)
            ->count();
        return ceil($count / $limit);
    }

    //总页数----软删除
    public static function totalSoftPage($table, $where)
    {
        $limit = config('verify.limit');
        $count = Db::name($table)
            ->where($where)
            ->useSoftDelete('delete_time')
            ->count();
        return ceil($count / $limit);
    }

    //绝对路径转化为相对路径
    public static function relationUrl($image)
    {
        $image_url = '';
        if (!empty($image)) {
            $host = config('verify.host');
            $image_url = str_replace($host, '', $image);
        }
        return $image_url;
    }

    //相对路径转绝对路径
    public static function absolutionUrl($image)
    {
        $image_url = '';
        if (!empty($image)) {
            $host = config('verify.host');
            if (strpos($image, 'http') === false) {
                $image_url = $host . $image;
            }else{
                $image_url = $image;
            }
        }
        return $image_url;
    }

    //get请求
    public static function http_get($url, $header = false)
    {
        $curl = curl_init();//启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, $header);//不开启header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        $result = curl_exec($curl); //执行操作
        curl_close($curl);
        return $result;
    }

    //post请求
    public static function http_post($url, $data)
    {
        $curl = curl_init();//启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, false); // 开启header
        //curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);//请求头部
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        $result = curl_exec($curl); //执行操作
        curl_close($curl);
        return $result;
    }

    /**
     * @param $member_id //用户id
     * @param $type //变动类型（0签到、1邀请新人、2被邀请人支付返还、3阅读文章、4观看视频、5提现球币、6投注消费、7投注返还本金、8投注返回盈利、9兑换商品）
     * @param $relate_id //关联id（0签到表id，1被邀请人id，2被邀请人支付订单id、3文章id。。。）
     * @param $detail //变动描述
     * @param $change_coin //本次变动球币
     * @param $afer_coin //变动后的球币
     * @return int|string
     */
    public static function changeCoin($member_id, $type, $relate_id, $detail, $change_coin, $afer_coin)
    {
        $data = [
            'member_id'     => $member_id,
            'type'          => $type,
            'relate_id'     => $relate_id,
            'change_detail' => $detail,
            'change_coin'   => $change_coin,
            'afer_coin'     => $afer_coin,
            'create_time'   => time(),
            'update_time'   => time(),
        ];
        return Db::name('change_coin')->insertGetId($data);
    }

    /**
     * @param $member_id //用户id
     * @param $change_coin  //改变的聊币
     * @param $afer_coin //改变后的聊币
     * @param $order_id //订单id
     * @return int|string
     */
    public static function changeTalkCoin($member_id, $change_coin, $afer_coin, $order_id=0)
    {
        $data = [
            'member_id'   => $member_id,
            'order_id'    => $order_id,
            'change_coin' => $change_coin,
            'afer_coin'   => $afer_coin,
            'create_time' => time(),
        ];
        return Db::name('change_talk_coin')->insertGetId($data);
    }

    //点赞或收藏
    public static function praise($where,$table)
    {
        //检查是否已点赞或收藏
        $is_praise = self::findWhereData('favorite', $where, 'id');
        $arr = [];
        if ($is_praise) {
            $arr['flag'] = false;
            if ($where['type'] == FavoriteModel::PRAISE) {
                //点赞
                $arr['msg'] = '你已经点过赞了';
            } else {
                //收藏
                $arr['msg'] = '你已经收藏过了';
            }
            return $arr;
        }

        $favoriteModel = new FavoriteModel();
        $res = $favoriteModel->allowField(true)->create($where);
        if ($res) {
            //增加表点赞数量
            if($where['type'] == FavoriteModel::PRAISE){
                if($table == 'home' || $table == 'talk' || $table == 'activity'){
                    Db::name($table)->where('id',$where['relation_id'])->setInc('praise_num',1);
                }
            }else{
                //增加个人中心收藏数量
                MemberModel::where('id',$where['member_id'])->setInc('collection_num',1);
            }
            $arr['flag'] = true;
            $arr['msg'] = '成功';
        } else {
            $arr['flag'] = false;
            $arr['msg'] = '失败';
        }
        return $arr;
    }

    //取消点赞或收藏
    public static function cancelPraise($where,$table)
    {
        $favoriteModel = new FavoriteModel();
        $res = $favoriteModel->where($where)->delete();
        if ($res) {
            //减少表点赞数量
            if($where['type'] == FavoriteModel::PRAISE){
                if($table == 'home' || $table == 'talk' || $table == 'activity'){
                    Db::name($table)->where('id',$where['relation_id'])->setDec('praise_num',1);
                }
            }else{
                //减少个人中心收藏数量
                MemberModel::where('id',$where['member_id'])->setDec('collection_num',1);
            }
            $arr['flag'] = true;
            $arr['msg'] = '取消成功';
        } else {
            $arr['flag'] = false;
            $arr['msg'] = '取消失败';
        }
        return $arr;
    }

    //获取属性
    public static function getAttr($table, $where, $field, $field1)
    {
        $res = CommonController::selectWhereData($table, $where, $field);
        $arr = [];
        foreach ($res as $value) {
            $arr[$value['id']] = $value[$field1];
        }
        return $arr;
    }

    //获取规则组属性
    public static function getSpecsAttr($res, $index, $attr_id = '', $parent_attr_id = '')
    {
        //查询规格组名称
        $arr_attr = [];
        $res_relation = CommonController::selectWhereData('shop_goods_relation', ['shop_goods_id' => $res['id'], 'shop_id' => $res['shop_id']], 'id,specs_attr', 'id asc');
        if ($res_relation) {
            $res_specs = CommonController::selectWhereData('specs', ['shop_id' => $res['shop_id']], 'id,specs_name', 'id asc');
            //查询规格对应的属性
            $res_attr = CommonController::getAttr('attr', ['shop_id' => $res['shop_id']], 'id,attr_name', 'attr_name');

            $arr = [];
            foreach ($res_specs as $r_s_key => $r_s_value) {
                $specs_attr_arr = [];
                if ($r_s_key != $index) {
                    continue;
                }

                foreach ($res_relation as $key => $value) {
                    $specs_attr = json_decode($value['specs_attr'], true);
                    if ($index == ShopGoodsModel::LEVEL_FIRST) {
                        //一级
                        foreach ($specs_attr as $s_a_value) {
                            if ($r_s_value['id'] == $s_a_value['specs_id']) {
                                $specs_attr_arr[$key] = $s_a_value['attr_id'];
                            }
                        }
                    } else if ($index == ShopGoodsModel::LEVEL_SECOND) {
                        //二级
                        $attr_ids = array_column($specs_attr, 'attr_id');
                        if (in_array($attr_id, $attr_ids)) {
                            array_push($specs_attr_arr, $attr_ids[1]);
                        }
                    } else {
                        //三级
                        $attr_ids = array_column($specs_attr, 'attr_id');
                        if (in_array($parent_attr_id, $attr_ids) && in_array($attr_id, $attr_ids)) {
                            array_push($specs_attr_arr, $attr_ids[2]);
                        }
                    }
                }

                $arr_specs = array_values(array_unique($specs_attr_arr));
                if ($r_s_key == $index) {
                    $arr_attr['id'] = $r_s_value['id'];
                    $arr_attr['specs_name'] = $r_s_value['specs_name'];
                    if ($index == ShopGoodsModel::LEVEL_SECOND) {
                        $arr_attr['parent_attr_id'] = $attr_id;
                    }
                    foreach ($arr_specs as $a_s_key => $a_s_value) {
                        $arr[$a_s_key]['attr_id'] = $a_s_value;
                        $arr[$a_s_key]['attr_name'] = $res_attr[$a_s_value];
                    }
                    $arr_attr['attr'] = $arr;
                    break;
                }
            }
        }
        return $arr_attr;
    }

    //获取规格组属性的库存价格
    public static function getSpecsPriceStock($res, $data)
    {
        $arr = [];
        if(isset($data['parent_attr_id'])){
            $parent_attr_id = $data['parent_attr_id'];
        }
        if(isset($data['second_attr_id'])){
            $second_attr_id = $data['second_attr_id'];
        }
        if(isset($data['third_attr_id'])){
            $third_attr_id = $data['third_attr_id'];
        }
        $res_relation = self::selectWhereData('shop_goods_relation', ['shop_goods_id' => $res['id'], 'shop_id' => $res['shop_id']], 'id,specs_attr,goods_coin,stock', 'id asc');
        if ($res_relation) {
            //判断规格层级
            $specs_count = self::totalWhere('specs', ['shop_id' => $res['shop_id']]);
            foreach ($res_relation as $key => $value) {
                $specs_attr = json_decode($value['specs_attr'], true);
                if ($specs_count == ShopGoodsModel::FIRST) {
                    //一级
                    $attr_ids = array_column($specs_attr, 'attr_id');
                    if (in_array($parent_attr_id, $attr_ids)) {
                        $arr['goods_coin'] = $value['goods_coin'];
                        $arr['goods_stock'] = $value['stock'];
                        $arr['goods_relation_id'] = $value['id'];
                        break;
                    }
                } else if ($specs_count == ShopGoodsModel::SECOND) {
                    //二级
                    $attr_ids = array_column($specs_attr, 'attr_id');
                    if (in_array($parent_attr_id, $attr_ids) && in_array($second_attr_id, $attr_ids)) {
                        $arr['goods_coin'] = $value['goods_coin'];
                        $arr['goods_stock'] = $value['stock'];
                        $arr['goods_relation_id'] = $value['id'];
                        break;
                    }
                } else {
                    //三级
                    $attr_ids = array_column($specs_attr, 'attr_id');
                    if (in_array($parent_attr_id, $attr_ids) && in_array($second_attr_id, $attr_ids) && in_array($third_attr_id, $attr_ids)) {
                        $arr['goods_coin'] = $value['goods_coin'];
                        $arr['goods_stock'] = $value['stock'];
                        $arr['goods_relation_id'] = $value['id'];
                        break;
                    }
                }
            }
        }
        return $arr;
    }

    //生成订单号
    public static function getOrderSn($letter = '')
    {
        $time = explode(" ", microtime());
        $timeArr = explode('.', $time [0]);
        $mtime = array_pop($timeArr);
        $res = $letter . $time[1] . $mtime . mt_rand(1000, 9999);
        return $res;
    }

    //返回两个日期之间相差的天数
    public static function interval_day($member_id)
    {
        //最近的签到数据
        $recentlySign = self::findWhereData('sign_record',['menber_id'=>$member_id],'','create_time desc');
        if (! $recentlySign){
             return true;
        }
        $start_date = date('Y-m-d',time());
        $end_date = date('Y-m-d',$recentlySign['create_time']);

        $datetime_start = new DateTime($start_date);
        $datetime_end = new DateTime($end_date);
        $days = $datetime_start->diff($datetime_end)->days;
        return $days;
    }
}
